package com.yue.yadmin.utils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;

import com.yue.yadmin.model.SysUser;

public class ShiroUtils {
	private static Logger logger = Log.getLogger(ShiroUtils.class);
	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}
	/**
	 * shiro登陆
	 * @param userName 账号
	 * @param password 密码
	 * @return
	 */
	public static Result login(String userName,String password){
		Result result = null;
		try {
			getSubject().login(new UsernamePasswordToken(userName, CommonUtils.getSha256Hash(password,userName)));
		    result = Result.ok();
		} catch (UnknownAccountException ex) {
			logger.info(ex.getMessage(),ex);
			result = Result.error(-1,"用户名或密码错误！");  
		} catch (LockedAccountException ex) {
			logger.info(ex.getMessage(),ex);
			result = Result.error(-2,"账户被禁用"); 
		} catch (IncorrectCredentialsException ex) {  
			logger.info(ex.getMessage(),ex);
			result = Result.error(-3,"用户名或密码错误！"); 
		}  catch (AuthenticationException ex) {
			logger.info(ex.getMessage(),ex);
			result = Result.error(-4,"登陆异常！"); 
		} catch (Exception ex) {
			logger.info(ex.getMessage(),ex);
			result = Result.error(-5,"登陆异常！"); 
		}
		return result;
	}
	public static void logout(){
		getSubject().logout();
	}
	/**
	 * 是否包含权限
	 * @param permission 单权限、多权限（逗号隔开）
	 * @return
	 */
	public static boolean hasPermission(String permission){
		String[] permissions = permission.split(",");
		for(String perm:permissions){
			try {
				getSubject().checkPermission(perm);
			} catch (AuthorizationException e) {
				return false;
			}
		}
		return true;
	}
	public static SysUser getUserEntity(){
		SysUser user = (SysUser)getSubject().getPrincipal();
		return user;
	}

	public static Long getUserId() {
		return getUserEntity().getId();
	}
}
